package lsp.receiver;

import lsp.base.LspPacket;
import lsp.base.MessageType;
import lsp.base.PacketStatus;
import lsp.connector.IConnector;

public class LspReceiver implements Runnable {
	
	private IConnector connector;
	
	public LspReceiver(IConnector connector) {
		this.connector = connector;
	}
	
	@Override
	public void run() {
		while (true) {
			LspPacket packet = connector.popReceivedLspPacket();
			if (packet != null) {
				if (packet.getMessageType() == MessageType.DATA) {
					connector.addReceivedExternalPack(packet.toPack());
					sendAck(packet.getConnId(), packet.getSequenceNumber());
				} else if (packet.getMessageType() == MessageType.ACK) {
					if (packet.getSequenceNumber() == 0) {
						connector.setConnectionId(packet.getConnId());
					} else if (connector.getCurrentLspPacket().getSequenceNumber() == packet.getSequenceNumber()) {
						connector.getCurrentLspPacket().setPacketStatus(PacketStatus.ACK_RECEIVED);
					}
				}
			}
			
			try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				// interrupted: terminate execution
				return;
			}
		}
	}

	private void sendAck(short connId, short sequenceNumber) {
		LspPacket lspPacket = new LspPacket(MessageType.ACK, connId, sequenceNumber);
		connector.sendPacket(lspPacket);
	}

}
